package com.vf.cloud.paas.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.springframework.core.io.ClassPathResource;
import com.jfinal.kit.StrKit;

public class MYSQLUtil {

	private static String installPath = "E:\\VFCloudPaaS";
	
	private static int port=23308;

	public static void main(String[] args) {
		
		boolean isStarted=startMYSQL(installPath,port);
		if(isStarted) {
			System.out.println("succeed");
		}else {
			System.out.println("faild");
		}
		
		
//		boolean isuninstalled=uninstallMYSQL(installPath);
//		if(isuninstalled) {
//			System.out.println("isuninstalled");
//		}else {
//			System.out.println("faild");
//		}
		
	}
	
	
	public static boolean startMYSQL(String softPath,int port) {
		if(query()) {
			 stop();
			 return start();
		}else {
			initIni(softPath,port);
			initialize(softPath);
			boolean isInstalled=install(softPath);
			if(!isInstalled) {
				return isInstalled;
			}
			boolean isStarted=start();
			
			if(isStarted) {
				createDbUser(softPath);
				String createCmd = String.format("%s/mysql/bin/mysql -u root  -P%s  < %s/mysql/creatDB.sql",softPath,port,softPath);
				executeCmd(createCmd, "CREATE_USER");
			}
			return isStarted;
		}
	}
	
	
	public static boolean  uninstallMYSQL(String softPath) {
		 stop();
		 return uninstall(softPath);
	}
	
	public static void  executeSQL(String softPath,int port,String sqlPath) {
		 executeCmd(String.format("%s/mysql/bin/mysql -u root -P%s  < %s",softPath,port,sqlPath), "executeSQL");
	}

	public static boolean initIni(String softPath,int port ) {
		File iniFile = new File(String.format("%s/mysql/my.ini", softPath));
		if (iniFile.exists()) {
			iniFile.delete();
		}
		BufferedWriter out = null;
		try {
			iniFile.createNewFile();
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(iniFile, false)));
			out.write("[mysqld]");
			out.newLine();
			out.write(String.format("port=%s", port));
			out.newLine();
			out.write(String.format("basedir=%s/mysql", softPath));
			out.newLine();
			out.write(String.format("datadir=%s/mysql/Data", softPath));
			out.newLine();
			out.write("max_connections=200");
			out.newLine();
			out.write("max_connect_errors=10");
			out.newLine();
			out.write("character-set-server=utf8");
			out.newLine();
			out.write("default-storage-engine=INNODB");
			out.newLine();
			out.write("default_authentication_plugin=mysql_native_password");
			out.newLine();
			out.write("[mysql]");
			out.newLine();
			out.write("default-character-set=utf8");
			out.newLine();
			out.write("[client]");
			out.newLine();
			out.write("port=23308");
			out.newLine();
			out.write("default-character-set=utf8");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
			}
		}
		return false;
	}
	
	/**
	 * 查询服务是否安装
	 * @return
	 */
	public static boolean query() {
		return executeCmd("SC QUERY \"VFCloudMySQL\" ", "SC_QUERY");
	}
	

	/**
	 * 初始化
	 * @param softPath
	 * @return
	 */
	public static boolean initialize(String softPath) {
		String cmd = String.format(
				"%s/mysql/bin/mysqld --defaults-file=%s/mysql/my.ini --initialize-insecure --console ", softPath,
				softPath);
		return executeCmd(cmd, "initialize");
	}

	/**
	 * install
	 * 
	 * @param softPath
	 * @return
	 */
	public static boolean install(String softPath) {
		String cmd = String.format("%s/mysql/bin/mysqld --install VFCloudMySQL", softPath);
		return executeCmd(cmd, "install");
	}

	/**
	 * start
	 * 
	 * @return
	 */
	public static boolean start() {
		String cmd = "net start VFCloudMySQL";
		return executeCmd(cmd, "start");
	}

	/**
	 * stop
	 * 
	 * @return
	 */
	public static boolean stop() {
		String cmd = "net stop VFCloudMySQL";
		return executeCmd(cmd, "stop");
	}

	/**
	 * remove
	 * 
	 * @param softPath
	 * @return
	 */
	public static boolean uninstall(String softPath) {
		String cmd = String.format("%s/mysql/bin/mysqld --remove VFCloudMySQL", softPath);
		return executeCmd(cmd, "uninstall");
	}

	public static boolean createDbUser(String softPath) {
		BufferedWriter out = null;
		try {
			String my = "use mysql;\r\n"
					+ "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'vfcloud@2022';\r\n"
					+ "flush privileges;";
			try {
				File f = new File(String.format("%s/mysql/creatDB.sql", softPath));
				if (f.exists()) {
					f.delete();
				}
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, true)));
				out.write(String.format(my, softPath, softPath));
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
			}
		}
		return false;
	}

	public static boolean createAppSQL(String softPath) {
		BufferedWriter out = null;
		InputStream in = null;
		BufferedReader br = null;
		try {
			try {
				File f = new File(String.format("%s/mysql/vfcloud.sql", softPath));
				if (f.exists()) {
					f.delete();
				}
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, true)));
				ClassPathResource resource = new ClassPathResource("/db/vfcloud.sql");
				in = resource.getInputStream();
				br = new BufferedReader(new InputStreamReader(in, "utf-8"));
				String line;
				while ((line = br.readLine()) != null) {
					out.write(line + " \r\n");
				}
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
				if (br != null)
					br.close();
				if (in != null)
					in.close();
			} catch (IOException e) {
			}
		}
		return false;
	}

	public static boolean executeCmd(String command, String type) {
		boolean isSucc = false;
		try {
			Runtime runtime = Runtime.getRuntime();
			Process process = runtime.exec("cmd /c start /b " + command);
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
			String line;
			while ((line = reader.readLine()) != null) {
				if (StrKit.equals("SC_QUERY", type)) {
					if (!StrKit.isBlank(line) && line.contains("VFCloudMySQL")) {
						isSucc = true;
					}
				} else if (StrKit.equals("install", type)) {
					if (!StrKit.isBlank(line) && line.contains("Service successfully installed")) {
						isSucc = true;
					}
				} else if (StrKit.equals("start", type)) {
					if (!StrKit.isBlank(line) && line.contains("VFCloudMySQL 服务已经启动成功")) {
						isSucc = true;
					}
				} else if (StrKit.equals("uninstall", type)) {
					if (!StrKit.isBlank(line) && line.contains("Service successfully removed")) {
						isSucc = true;
					}
				}
			}
			process.waitFor();
		} catch (InterruptedException | IOException e) {
		}
		return isSucc;
	}

}
